import { useLoginStore } from '@/stores/login'


const genOption = (reqOptions: any) => {
  const { token } = useLoginStore()
  const { method, data } = reqOptions
  let fetchMethod = method
  //  ['options', 'get', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'head', 'patch', 'post', 'put', 'delete', 'connect', 'trace']
  const methodTypes = ['get', 'GET', 'PATCH', 'POST', 'PUT', 'DELETE', 'patch', 'post', 'put', 'delete']
  if (!method || !methodTypes.includes(method)) {
    fetchMethod = 'get'
  }
  const fetchOptions: any = {
    method: fetchMethod,
    ...reqOptions,
  }
  if (isNotNilOrEmpty(data)) {
    fetchOptions.data = data
  }
  fetchOptions.header = reqOptions?.headers || {}
  if (isNotNilOrEmpty(token)) {
    fetchOptions.header.token = token
  }
  return fetchOptions
}

// 标准请求工具，分离 url，数据和请求设置。仅限客户端使用
export const Fetch = async (url: string, reqOptions: any = {}): Promise<{
  status: number
  data: any
  error: any
}> => {
  let data, error, status
  const reqUrl = /^https?:/.test(url) ? url : `${baseUrl}${url}`
  await request({
    url: reqUrl,
    ...genOption(reqOptions),
    complete: (res: any) => {
      status = res.statusCode
      error = res.errMsg
      data = res.data
    },
  })
  if (data.code !== 0) {
    if (data.code === 401) {
      uni.showToast({
        title: '正在前往登录',
        icon: 'error',
        duration: 1600,
      })
      setTimeout(() => {
        //uni.reLaunch({ url: '/pages/login' })
      }, 1600)
      return { status, data, error }
    }
    if (data.code === 500 || data.code === 75301 || data.code === -1 || data.code === 400) return { status, data, error }
    uni.showToast({
      title: data.msg,
      icon: 'none',
      duration: 1600,
    })
  }
  return { status, data, error }
}

export const getFetch = (data): Promise<any> => {
  return Fetch('/api/crud/get', { method: 'post', data })
}

export const upsertFetch = (data): Promise<any> => {
  return Fetch('/api/crud/upsert', { method: 'post', data })
}

export const pgUpsertFetch = (schema, table, data): Promise<any> => {
  return Fetch(`/api/pg/upsert/${schema}/${table}`, { method: 'put', data })
}

// 单表数据查询 apijson 接口
export const tableFetch = async (tableName, reqData: any = {}): Promise<any> => {
  const { schema, table } = parseTableName(tableName)
  if (isNilOrEmpty(table)) {
    return { status: 400, error: '传参错误', data: null }
  }

  const limit = reqData.limit ? reqData.limit : 50
  const offset = reqData.offset ? reqData.offset : 0
  const formDataParse = clone(reqData)
  delete formDataParse.limit
  delete formDataParse.offset
  const data = {
    format: true,
    'data[]': {
      [capitalCase(table)]: {
        ...formDataParse,
      },
      page: Math.floor(offset / limit),
      query: 2,
      count: limit,
    },
    'info@': '/data[]/info',
  }
  if (isNotNilOrEmpty(schema)) {
    data['data[]'][capitalCase(table)]['@schema'] = schema
  }
  const resp = await Fetch('/api/crud/get', { method: 'post', data })
  return parseRespData(resp)
}
